package com.ericxu.weixin;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class Authentication {
	private static final String TOKEN = "weixin";
	/**
	 * Function: 微信验证方式
	 * @author Eric
	 * @param signature 微信加密签名
	 * @param timestamp 时间戳
	 * @param nonce 随机数
	 */
	public static boolean checkAuthentication(String signature, String timestamp, String nonce) {
		String[] params = {TOKEN, timestamp, nonce};
		Arrays.sort(params);
		String strEncrypt = params[0] + params[1] + params[2];
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(strEncrypt.getBytes());
			String shaSign = bytes2Hex(md.digest());
			if (shaSign.equals(signature)) {
				return true;
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	private static String bytes2Hex(byte[] bts) {
		String dest = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				dest += "0";
			} else {
				dest += tmp;
			}
		}
		
		return dest;
	}
}
